package com.example.crm_system.service.impl;

import com.example.crm_system.config.JwtTokenUtils;
import com.example.crm_system.entity.Params;
import com.example.crm_system.entity.User;
import com.example.crm_system.exception.MyOwnException;
import com.example.crm_system.mapper.UserMapper;
import com.example.crm_system.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void insert(User user) {
        if (user.getEname() == null || user.getEname().isEmpty()) {
            throw new MyOwnException("员工姓名不能为空");
        }
        if (user.getAccount() == null || user.getAccount().isEmpty()) {
            throw new MyOwnException("账号不能为空");
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new MyOwnException("密码不能为空");
        }
        User userAccount = userMapper.selectByAccount(user.getAccount());
        if (userAccount != null) {
            throw new MyOwnException("此账号已存在");
        }
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(Integer eno) {
        userMapper.delete(eno);
    }

    @Override
    public PageInfo<User> searchUser(Params params) {
        // 开启分页查询功能
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        // 接下来的查询会自动按照当前开启的分页设置来查询
        List<User> list = userMapper.searchUser(params);
        return PageInfo.of(list);
    }

    public User login(@RequestBody User user){
        // 非空判断
        if (user.getAccount() == null || user.getAccount().isEmpty()) {
            throw new MyOwnException("账号不能为空");
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new MyOwnException("密码不能为空");
        }
        User login =  userMapper.findByAccountAndPassword(user.getAccount(), user.getPassword());
        // 非空判断
        if (login == null) {
            throw new MyOwnException("用户名或密码输入错误");
        }
        String token = JwtTokenUtils.genToken(login.getEno().toString(), login.getPassword());
        login.setToken(token);
        return login;
    }

    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }

}
